<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use App\Models\V1\AdminUser;
use App\Models\V1\Custodians;
use App\Models\V1\WeChatLogin;
use App\Models\V1\NewStudent;
use App\Models\V1\ScrollImages;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Log;

class SmallProgramController extends BaseController{
    
    protected $app_id = 'wx6397396df988f501';
    protected $app_secret = 'f767a74b8fa834acbdf55971e858cb81';
    
    /**
     * 小程序端注册接口
     */
    public function register(Request $request){
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        //接收传递参数
        $reqParams = $request -> all();
        
        //获取basic_wechat_login表中数据
        $wechat_info = WeChatLogin::get();
        for($i=0;$i<count($wechat_info);$i++){
            
            if($reqParams['examCode'] == $wechat_info[$i]->exam_code){
                $result['errorMsg'] = '您的考试号已存在';
                return $result;
            }
        }
        //获取basic_new_student表中的数据
        $new_student_info = NewStudent::get();
        for($i=0;$i<count($new_student_info);$i++){
            if($reqParams['idNumber'] == $new_student_info[$i]->card_number){
                $result['errorMsg'] = '您的身份账号已经存在';
                return $result;
            }
        }
        
        // 注册接口
        $successFlag = $this->handleRegister($reqParams);
        if ($successFlag) {
            $result['errorMsg'] = '注册成功';
            $result['errorCode'] = Response::HTTP_OK;
        }else{
            $result['errorMsg'] = '注册失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }
    
    private function handleRegister(array $params){
        $name       = isset($params['name']) ? $params['name'] : '';            //姓名
        $id_number  = isset($params['idNumber']) ? $params['idNumber'] : '';    //身份证号(唯一)
        $exam_code  = isset($params['examCode']) ? $params['examCode'] : '';    //准考证号(唯一)
        $password   = isset($params['password']) ? $params['password'] : '';    //密码
        $js_code    = isset($params['jsCode']) ? $params['jsCode'] : '';      //json code
        $encrypted_data = isset($params['encryptedData']) ? $params['encryptedData'] : '';
        $iv = isset($params['iv']) ? $params['iv'] : '';
        $third_session = isset($params['thirdSession']) ? $params['thirdSession'] : '';
        
        $apiStr = 'sns/jscode2session?appid='.$this->app_id.'&secret='.$this->app_secret.'&js_code='.$js_code.'&grant_type=authorization_code';
        
        //获取小程序openid
        $resultData = $this -> weixinGet($apiStr, []);
        $resultData = json_decode($resultData, true);
        
        //赋值openid
        $openid = $resultData['openid'];

        //学生信息录入
        $successFlag0 = NewStudent::insert([
            'arrival_code' => '201720180202',
            'enrollment_numbering' => '',
            'exam_code' => $exam_code,
            'name' => $name,
        ]);

        //微信学生信息录入
        $successFlag = WeChatLogin::insert([
            'unionid' => $openid,
            'openid' => $openid,
            'exam_code' => $exam_code,
        ]);

        //学生用户录入
        $successFlag1 = AdminUser::insert([
            'code' => $exam_code,
            'password' => bcrypt($password),
            'is_staff' => 0,
        ]);

        if(($successFlag0 == true)&&($successFlag == true)&&($successFlag1 == true)){
            return 1;
        }else{
            return 0;
        }
    }
    
    //get 微信接口
    public function weixinGet($apiStr, $header)
    {
        $client = new \GuzzleHttp\Client(['base_uri' => 'https://api.weixin.qq.com/']);
        $res = $client->request('GET', $apiStr, ['headers' => $header]);
        $statusCode = $res->getStatusCode();
        $header = $res->getHeader('content-type');

        $data = $res->getBody();

        return $data;
    }
}
